<template>
  <div class="product-detail">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="product" class="detail-container">
      <div class="product-images">
        <img :src="product.image" alt="产品图片" class="product-image" />
        <div v-if="product.images && product.images.length > 1" class="thumbnail-images">
          <img 
            v-for="(img, index) in product.images" 
            :key="index" 
            :src="img" 
            :alt="'产品图片' + (index + 1)" 
            class="thumbnail"
            @click="product.image = img"
          />
        </div>
      </div>
      <div class="product-info">
        <div class="product-category">{{ product.categoryName || '未分类' }}</div>
        <h1 class="product-name">{{ product.name }}</h1>
        <div class="product-rating">
          <span class="star" v-for="i in 5" :key="i" :class="{ filled: i <= 4.8 }">★</span>
          (4.8) 256条评价
        </div>
        <div class="product-price">
          ¥{{ product.price }}
          <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
          <span v-if="product.originalPrice" class="discount">省¥{{ product.originalPrice - product.price }}</span>
        </div>
        
        <div class="product-description">
          <h3>产品描述</h3>
          <p>{{ product.description || product.shortDescription || '暂无描述' }}</p>
        </div>
        
        <div class="product-features">
          <h3>产品特性</h3>
          <div class="feature-item">✔ 库存：{{ product.stock || 0 }}件</div>
          <div class="feature-item">✔ SKU：{{ product.sku || '未知' }}</div>
          <div v-if="product.weight" class="feature-item">✔ 重量：{{ product.weight }}kg</div>
          <div v-if="product.dimensions" class="feature-item">✔ 尺寸：{{ product.dimensions }}</div>
        </div>
        
        <div class="quantity-selector">
          <label>数量：</label>
          <div class="quantity-controls">
            <button @click="updateQuantity(-1)" :disabled="quantity <= 1">-</button>
            <span class="quantity-display">{{ quantity }}</span>
            <button @click="updateQuantity(1)" :disabled="quantity >= (product.stock || 10)">+</button>
          </div>
          <span class="stock-info">库存：{{ product.stock || 10 }}件</span>
        </div>
        
        <div class="action-buttons">
          <button class="btn-buy" @click="buyNow">立即购买</button>
          <button class="btn-cart" @click="addToCart">加入购物车</button>
        </div>
      </div>
    </div>
    <div v-else class="error">产品不存在</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCartStore } from '../stores/cart'
import { productAPI } from '../services/api'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const product = ref(null)
const loading = ref(false)
const quantity = ref(1)

// 根据id获取产品详情
const getProductDetail = async (id) => {
  loading.value = true
  try {
    const response = await productAPI.getProduct(id)
    if (response.success && response.data.product) {
      const productData = response.data.product
      product.value = {
        id: productData.id,
        name: productData.name,
        price: productData.price,
        originalPrice: productData.originalPrice,
        description: productData.description,
        shortDescription: productData.shortDescription,
        stock: productData.stock,
        sku: productData.sku,
        weight: productData.weight,
        dimensions: productData.dimensions,
        categoryName: productData.category?.name,
        image: productData.images?.[0] || 'https://picsum.photos/300/400?random=10',
        images: productData.images && productData.images.length > 0 
          ? productData.images 
          : ['https://picsum.photos/300/400?random=10']
      }
    } else {
      product.value = null
    }
  } catch (error) {
    console.error('加载产品详情失败:', error)
    // 备用数据
    const mockProducts = [
      { id: 1, name: '智能手机', price: 2999, image: 'https://picsum.photos/300/400?random=10', images: ['https://picsum.photos/300/400?random=10'] },
      { id: 2, name: '无线耳机', price: 599, image: 'https://picsum.photos/300/400?random=11', images: ['https://picsum.photos/300/400?random=11'] },
      { id: 3, name: '智能手表', price: 1299, image: 'https://picsum.photos/300/400?random=12', images: ['https://picsum.photos/300/400?random=12'] },
      { id: 4, name: '笔记本电脑', price: 5999, image: 'https://picsum.photos/300/400?random=13', images: ['https://picsum.photos/300/400?random=13'] }
    ]
    product.value = mockProducts.find(item => item.id === parseInt(id)) || null
  } finally {
    loading.value = false
  }
}

// 加入购物车
const addToCart = () => {
  if (product.value) {
    for (let i = 0; i < quantity.value; i++) {
      cartStore.addToCart(product.value)
    }
    alert(`已添加 ${quantity.value} 件商品到购物车！`)
  }
}

// 立即购买
const buyNow = () => {
  if (product.value) {
    cartStore.clearCart()
    for (let i = 0; i < quantity.value; i++) {
      cartStore.addToCart(product.value)
    }
    router.push({ name: 'Orders' })
  }
}

// 更新数量
const updateQuantity = (change) => {
  const newQuantity = quantity.value + change
  if (newQuantity >= 1 && newQuantity <= (product.value?.stock || 10)) {
    quantity.value = newQuantity
  }
}

onMounted(() => {
  getProductDetail(route.params.id)
})
</script>

<style scoped>
.product-detail {
  padding: 40px 20px;
  min-height: 80vh;
}
.detail-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 产品图片区域 */
.product-images {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.product-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
}
.thumbnail-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.thumbnail {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}
.thumbnail:hover {
  border-color: #6a4a9e;
}

/* 产品信息区域 */
.product-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.product-category {
  color: #6a4a9e;
  font-size: 14px;
  margin-bottom: 8px;
}
.product-name {
  font-size: 32px;
  margin-bottom: 16px;
  line-height: 1.2;
}
.product-rating {
  color: #ffc107;
  margin-bottom: 24px;
}
.star.filled {
  color: #ffc107;
}
.product-price {
  font-size: 28px;
  font-weight: bold;
  color: #e64340;
  margin-bottom: 24px;
}
.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-left: 8px;
}
.discount {
  background: #e64340;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  margin-left: 8px;
}

/* 产品描述和特性 */
.product-description {
  margin-bottom: 24px;
}
.product-description h3 {
  font-size: 18px;
  margin-bottom: 8px;
  color: #333;
}
.product-description p {
  color: #666;
  line-height: 1.6;
}

.product-features {
  background: #f9fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}
.product-features h3 {
  font-size: 18px;
  margin-bottom: 12px;
  color: #333;
}
.feature-item {
  margin-bottom: 8px;
  color: #555;
}

/* 数量选择器 */
.quantity-selector {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-controls button {
  width: 36px;
  height: 36px;
  border: none;
  background: #f8f9fa;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s;
}

.quantity-controls button:disabled {
  background: #f0f0f0;
  cursor: not-allowed;
  color: #ccc;
}

.quantity-controls button:hover:not(:disabled) {
  background: #e9ecef;
}

.quantity-display {
  width: 50px;
  text-align: center;
  font-weight: bold;
}

.stock-info {
  color: #666;
  font-size: 14px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}
.btn-buy, .btn-cart {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  flex: 1;
}
.btn-buy {
  background: #e64340;
  color: white;
}
.btn-buy:hover {
  background: #d63031;
}
.btn-cart {
  background: #6a4a9e;
  color: white;
}
.btn-cart:hover {
  background: #5a3a8e;
}

/* 加载和错误状态 */
.loading, .error {
  text-align: center;
  font-size: 18px;
  color: #666;
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  .action-buttons {
    flex-direction: column;
  }
  .product-image {
    height: 300px;
  }
}
</style>